package com.leo.javase.thread.blog;

public class TestProducerConsumer {
	public static void main(String[] args) {
		Queue queue = new Queue();
		new Producer(queue).start();
		new Consumer(queue).start();
	}
}
/**
 * 生产者
 * @author Administrator
 */
class Producer extends Thread{
	private Queue queue;
	
	public Producer(Queue queue) {
		this.queue = queue;
	}
	
	@Override
	public void run() {
		for(int i=0; i<10; i++){
			queue.setValue(i);
			System.out.println("producer--"+i);
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
/**
 * 消费者
 * @author Administrator
 */
class Consumer extends Thread{
	private Queue queue;
	
	public Consumer(Queue queue) {
		this.queue = queue;
	}
	
	@Override
	public void run() {
		while(true){
			System.out.println("consumer--"+queue.getValue());
		}
	}
}
class Queue{
	private int value = 0;
	private boolean isFull = false;
	//两个同步方法加的锁的对象都是this，必须是同一个对象
	public synchronized void setValue(int value){
		//阻塞队列没有满，则设置数据，并且通知cusumer取数据
		if(!isFull){
			this.value = value;
			notify();
			isFull = true;
		}
		//队列已满，则等待
		try {
			wait();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	//两个同步方法加的锁的对象都是this，必须是同一个对象
	public synchronized int getValue(){
		//阻塞队列已满，则设置等待
		if(!isFull){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		isFull = false;
		notify();
		return value;
	}
}


